/**
 * Created by easy on 15/5/15.
 */
$(document).ready(function () {
    pullToRefresh.init({
        loadingFunction: util.pullToRefresh
    });
    var params = mc.getParamsFromURL(window.location);
    vars.processID = params.processID;
    vars.processName = params.processName;
    vars.orderID = params.orderID;
    vars.ractiveOrderSubProcessList = new Ractive({
        el:"CONTAINER-subprocess",
        template:"#TEMPLATE-subprocess",
        data:{ractiveData:[],formatDate:function(time,format){
            return mc.dealTime(parseInt(time),format);
        }}
    });
    vars.ractiveProcessRemark = new Ractive({
        el:"CONTAINER-processremark",
        template:"#TEMPLATE-processremark",
        data:{
            ractiveData:[],
            formatDate:function(time,format){ return mc.dealTime(parseInt(time),format); },
            processName: vars.processName
        }
    });
});
(function () {
    basic.deviceReady = function () {

        util.getOrderSubProcessList(function () {
            util.syncAbnormalsData(util.getOrderSubProcessList);
        })
        $("#btn-addremark").show();
    };
    //下拉刷新（同步数据后 显示列表）
    util.pullToRefresh = function () {
        util.getOrderSubProcessList(function () {
            util.syncAbnormalsData(pullToRefresh.reset);
        })
    };
    util.syncAbnormalsData = function(callback){
        mc.syncData(["QC_PROCESS","QC_SUBPROCESS","QC_REMARK"],callback);
    };
    util.changeDate = function (touchObj, dateType, subprocessID, subprocessName) {
        vars.subprocessID = subprocessID;
        vars.subprocessName = subprocessName;
        if ($(touchObj).val() != "") {
            var date = mc.dealTime($(touchObj).val(), "yyyy-MM-dd");
            $(touchObj).siblings("span").html(date)
        }
        date = new Date(date).getTime();
        util.changeDateSubmit(dateType, date);
    }

    util.getOrderSubProcessList = function (callback) {
        var getOrderSubProcessListCallback = function (data) {
            //alert(JSON.stringify(data))
            vars.ractiveOrderSubProcessList.data.ractiveData = data;
            vars.ractiveOrderSubProcessList.update("ractiveData");
            util.getOrderProcessRemarkList(function () {
                mc.showContent();
            })
            //util.showPhotos(data);
            if (callback != undefined) {
                callback()
            }
        };
        var options = {
            processID: vars.processID
        };
        service.getSubProcessData(options, getOrderSubProcessListCallback)
    };

    util.getOrderProcessRemarkList = function (callback) {
        var getOrderProcessRemarkListCallback = function (data) {
            //alert(JSON.stringify(data))
            vars.ractiveProcessRemark.data.ractiveData = data;
            vars.ractiveProcessRemark.update("ractiveData");

            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfProcessRemarkList
            };
            common.morePage(optionsForMorePage);
            //util.showPhotos(data);
            if (callback != undefined) {
                callback()
            }
        };
        var optionsForInitScrollList = {
            mode: "normal",
            scrollContainer: $("#content")
        };
        common.initScrollList(optionsForInitScrollList);
        var options = {
            processID: vars.processID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getProcessRemarkData(options, getOrderProcessRemarkListCallback)
    };
    util.paginationOfProcessRemarkList = function () {
        var paginationOfProcessRemarkListCallback = function (data) {
            vars.ractiveProcessRemark.data.ractiveData = $.merge(vars.ractiveProcessRemark.data.ractiveData, data);
            vars.ractiveProcessRemark.update("ractiveData");
            var optionsForMorePage = {
                mode: "normal",
                dataLength: data.length,
                scrollContainer: $("#content"),
                callback: util.paginationOfProcessRemarkList
            };
            common.morePage(optionsForMorePage);
            //util.showPhotos(data);
        };
        var options = {
            processID: vars.processID,
            currentPage: vars.currentPage,
            pageSize: vars.pageSize
        };
        service.getProcessRemarkData(options, paginationOfProcessRemarkListCallback)
    };
    vars.inTheSubmit = false;
    util.changeDateSubmit = function (dateType, date) {
        var type = "remindDate"
        if (vars.inTheSubmit == false) {
            vars.inTheSubmit = true;
        } else {
            return false
        }
        var submitCallback = function (data) {
            if (data.result == true) {
                vars.inTheSubmit = false;
                util.getOrderSubProcessList();
            }
        };
        var time = new Date().getTime();
        var requestData = {
            "id": vars.subprocessID,
            "remindDate": date,
            "lastModifiedByUserLogin": vars.userInfo.username,
            "lastUpdateTime": time
        };
        if (dateType == "完成时间") {
            type = "actualTime";
            requestData = {
                "id": vars.subprocessID,
                "actualTime": date,
                "lastModifiedByUserLogin": vars.userInfo.username,
                "lastUpdateTime": time
            };
        }
        var extraData = {
            "person": vars.userInfo.username,
            "action": "修改了" + vars.subprocessName + "的" + dateType + "为" + mc.dealTime(parseInt(date),"yyyy-MM-dd"),
            "content": [{"text": ""}]
        };
        //提交前向主数据异常表 修改指定异常
        var SQLOfUpdateSubProcess = "UPDATE QC_SUBPROCESS SET " + type + "Edit = '" + date + "'," + type + "Status = ?, lastModifiedByUserLogin = '" + vars.userInfo.username + "'," +
            "lastUpdateTime='" + time + "' WHERE jsonPK = '" + vars.subprocessID + "';";

        //前向主数据动态表 插入一条到全部历史
        /*var SQLOfInsertAbnormalToDynamic = "INSERT INTO QC_DYNAMIC " +
         "(jsonPK, matchID, description, createdName,lastUpdateTime, attachment, type) VALUES" +
         " ('remark" + time + "', '" + vars.abnormalID + "', '" + content + "','" + vars.userInfo.username + "','" + time + "','" + JSON.stringify(vars.submitPhotosArray) + "',2 );";
         */
        //提交后修改异常状态
        var SQLOfChangeSubProcessStatus = "UPDATE QC_SUBPROCESS SET " + type + "Status = ? WHERE jsonPK = '" + vars.subprocessID + "';";

        //提交前后 修改订单表状态
        var SQLOfChangeOrderStatus = "UPDATE QC_ORDER SET processStatus = CASE " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
            "ELSE 'success1' END WHERE jsonPK = '" + vars.orderID + "';";

        //提交前后 修改流程表状态
        var SQLOfChangeProcessStatus = "UPDATE QC_PROCESS SET subProcessStatus = CASE " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.processID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.processID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
            "ELSE 'success' END WHERE jsonPK = '" + vars.processID + "';";

        //var SQLOfChangeOrderStatus = "UPDATE tab_Order SET remark_status = 'test1111' WHERE json_pk = '"+vars.orderID+"';";
        var params = {
            URL: service.url + "/orderSubProcess/updateOrderSubProcess",
            HTTPMethod: "post",
            requestData: requestData,
            extra: extraData,
            uploadAttachmentFilesInfo: [],
            matchIDs: vars.processID + "," + vars.orderID,
            SQLOperation: {
                SQLOfAjaxStarted: SQLOfUpdateSubProcess + SQLOfChangeOrderStatus + SQLOfChangeProcessStatus,
                SQLOfAjaxCompleted: SQLOfChangeSubProcessStatus + SQLOfChangeProcessStatus + SQLOfChangeOrderStatus
            },
            noticePages: ["detail.html", "orders.html", "dynamic.html", "sub-process.html"]
        };

        mc.submitToAjaxWorker(params, submitCallback)
    }

    util.changeSubProcessStatus = function (status, subprocessID, subprocessName) {
        if (vars.inTheSubmit == false) {
            vars.inTheSubmit = true;
        } else {
            return false
        }
        var submitCallback = function (data) {
            if (data.result == true) {
                vars.inTheSubmit = false;
                util.getOrderSubProcessList();
            }
        };
        var time = new Date().getTime();
        var requestData = {
            "id": subprocessID,
            "status": status,
            "actualTime": status == 'T' ? time : '1000',
            "lastModifiedByUserLogin": vars.userInfo.username,
            "lastUpdateTime": time
        };
        var extraData = {
            "person": vars.userInfo.username,
            "action": status == "T" ? "完成了子流程：" + subprocessName : "取消了子流程："+ subprocessName + "的完成状态",
            "content": [{"text": ""}]
        };
        //提交前向主数据异常表 修改指定异常
        var SQLOfUpdateSubProcess = "UPDATE QC_SUBPROCESS SET statusEdit = '" + status + "',statusStatus = ?,actualTimeEdit = '" + (status == 'T' ? time : "1000") + "'," +
            "actualTimeStatus = ?, lastModifiedByUserLogin = '" + vars.userInfo.username + "', lastUpdateTime='" + time + "' WHERE jsonPK = '" + subprocessID + "';";

        //前向主数据动态表 插入一条到全部历史
        /*var SQLOfInsertAbnormalToDynamic = "INSERT INTO QC_DYNAMIC " +
         "(jsonPK, matchID, description, createdName,lastUpdateTime, attachment, type) VALUES" +
         " ('remark" + time + "', '" + vars.abnormalID + "', '" + content + "','" + vars.userInfo.username + "','" + time + "','" + JSON.stringify(vars.submitPhotosArray) + "',2 );";
         */
        //提交后修改异常状态
        var SQLOfChangeSubProcessStatus = "UPDATE QC_SUBPROCESS SET statusStatus = ?,actualTimeStatus = ? WHERE jsonPK = '" + subprocessID + "';";

        //提交前后 修改订单表状态
        var SQLOfChangeOrderStatus = "UPDATE QC_ORDER SET processStatus = CASE " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.orderID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
            "ELSE 'success' END WHERE jsonPK = '" + vars.orderID + "';";

        //提交前后 修改流程表状态
        var SQLOfChangeProcessStatus = "UPDATE QC_PROCESS SET subProcessStatus = CASE " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.processID + "%' AND FCloudDataTransferState = 'uploading') > 0) THEN 'uploading' " +
            "WHEN ((SELECT count(1) FROM T_CloudDataTransferCenter WHERE FCloudDataTransferMatchIDs LIKE '%" + vars.processID + "%' AND FCloudDataTransferState = 'failed') > 0) THEN 'failed' " +
            "ELSE 'success' END WHERE jsonPK = '" + vars.processID + "';";

        //var SQLOfChangeOrderStatus = "UPDATE tab_Order SET remark_status = 'test1111' WHERE json_pk = '"+vars.orderID+"';";
        var params = {
            URL: service.url + "/orderSubProcess/updateOrderSubProcess",
            HTTPMethod: "post",
            requestData: requestData,
            extra: extraData,
            uploadAttachmentFilesInfo: [],
            matchIDs: vars.orderID + "," + vars.processID,
            SQLOperation: {
                SQLOfAjaxStarted: SQLOfUpdateSubProcess + SQLOfChangeOrderStatus + SQLOfChangeProcessStatus,
                SQLOfAjaxCompleted: SQLOfChangeSubProcessStatus + SQLOfChangeOrderStatus + SQLOfChangeProcessStatus
            },
            noticePages: ["detail.html", "orders.html", "dynamic.html"]
        };

        mc.submitToAjaxWorker(params, submitCallback)
    }

    util.addProcessRemark = function () {
        mc.jump('submit.html?submitType=6&type=2&objID='+vars.processID+'&orderID='+vars.orderID,'添加流程备注','SubmitModal');
    }
    util.editProcessRemark = function (remarkID) {
        for(var i = 0; i<vars.ractiveProcessRemark.data.ractiveData.length;i++ ){
            if(vars.ractiveProcessRemark.data.ractiveData[i].jsonPK == remarkID){
                mc.saveDataToLocalStorage("submitData", vars.ractiveProcessRemark.data.ractiveData[i], function (data) {
                    mc.jump('submit.html?submitType=7&type=2&processID='+vars.processID+'&orderID='+vars.orderID,'编辑流程备注','SubmitModal');
                }, "app");
            }
        }
    }
})();